package jp.syuriken.snsw.lancher;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;

import jp.syuriken.snsw.terenaibot.BotSystem;
import jp.syuriken.snsw.terenaibot.internal.ConfigurationException;
import jp.syuriken.snsw.utils.Logger;

/**
 * TerenaiBotSystemを起動するためのランチャー。
 * 
 * @author $Author: SnSoftware $
 */
public class TerenaiBotSystemLancher {
	
	private static boolean isFinish = false;
	
	private static Logger logger;
	
	private static BotSystem bt;
	

	/**
	 * 起動。
	 * 
	 * @param args オプションを格納した配列。
	 */
	public static void main(String[] args) {
		try {
			logger = Logger.getLogger("tbotsys.log", Level.ALL);
			bt = new BotSystem(logger);
		} catch (FileNotFoundException e) {
			System.err.println(e.getLocalizedMessage());
			System.exit(1);
			return;
		} catch (ConfigurationException e) {
			System.err.println(e.getLocalizedMessage());
			System.exit(1);
			return;
		} catch (IOException e) {
			System.err.println(e.getLocalizedMessage());
			System.exit(1);
			return;
		}
		bt.start();
		Runtime.getRuntime().addShutdownHook(new Thread() {
			
			@Override
			public void run() {
				isFinish = true;
				bt.stopBot();
				try {
					bt.join();
				} catch (InterruptedException e) {
					// do nothing
				}
				try {
					logger.flush();
				} catch (IOException e) {
					System.err.println(e.getLocalizedMessage());
				}
				try {
					logger.close();
				} catch (IOException e) {
					System.err.println(e.getLocalizedMessage());
				}
			}
		});
		
		do {
			try {
				bt.join();
			} catch (InterruptedException e) {
				// do nothing
			}
		} while (!isFinish);
	}
	
	private TerenaiBotSystemLancher() {
	}
}
